﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Yz.Base;
using Yz.Base.Config;
using Yz.Core.Extensions;
using Yz.DB.EFCore.Dal;
using Yz.Model.Constants;
using Yz.Model.Entities;
using Yz.Model.Enums;
using Yz.Model.Views;

namespace Yz.Manage.Controllers
{
    [AllowAnonymous]
    public class AccountController : BaseController
    {
        private readonly IDbAccess<User> _userDbAccess;
        private readonly JwtConfig _jwtConfig;
        public AccountController(
            IDbAccess<User> userDbAccess,
            IOptions<JwtConfig> jwtConfigOptions)
        {
            _userDbAccess = userDbAccess;
            _jwtConfig = jwtConfigOptions.Value;
        }
        /// <summary>
        /// 未登录状态下的首页
        /// </summary>
        /// <returns></returns> 
        [Route("account/index")]
        [Route("home/index")]
        public IActionResult Index()
        {
            return View();
        }

        #region 登录注销
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns> 
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public async Task<JsonResult> LoginUser(string lgnName, string lgnPwd, string code)
        {
            if (string.IsNullOrEmpty(lgnName) || string.IsNullOrEmpty(lgnPwd) || string.IsNullOrEmpty(code))
            {
                return Json(new { Suc = false, Msg = "用户名、密码、验证码不能为空！" });
            }
            string sessionCode = GetSessionCheckCode();
            if (sessionCode == null || sessionCode.ToLower() != code.ToLower())
            {
                return Json(new { Suc = false, Msg = "验证码不正确！" });
            }
            lgnPwd = lgnPwd.ToMd5Hash();
            var vUser = await _userDbAccess.GetModelAsync<VmUserBase>(p => p.LoginName == lgnName && p.LoginPwd == lgnPwd && p.StatusType == StatusType.Enable);

            if (vUser != null)
            {
                List<string> roleList = base.GetRoleList(vUser.UserType);
                string url = "";
                switch (vUser.UserType)
                {
                    case UserType.Staff:
                        url = "/student/apply";
                        break;
                    case UserType.CompanyAdmin:
                        url = "/student/index";
                        break;
                    case UserType.Admin:
                        url = "/notice/index";
                        break;
                }
                string token = JwtManager.GenerateToken(vUser, roleList, _jwtConfig);
                Response.Cookies.Append("access_token", token);
                return Json(new { Suc = true, Msg = "登录成功！", url = url });
            }
            return Json(new { Suc = false, Msg = "用户名或者密码错误！" });
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns> 
        public IActionResult LogOff()
        {
            Response.Cookies.Delete("access_token");
            return Redirect("/Account/index");
        }

        #endregion

        #region 错误提示页面
        /// <summary>
        /// 错误页面
        /// </summary>
        /// <returns></returns> 
        public IActionResult Error()
        {
            return View();
        }
        /// <summary>
        /// 非法登录
        /// </summary>
        /// <returns></returns> 
        public IActionResult Illegal()
        {
            return View();
        }

        #endregion

        /// <summary>
        /// 更新说明页面
        /// </summary>
        /// <returns></returns> 
        [Route("account/about")]
        [Route("home/about")]
        public IActionResult About()
        {
            return View();
        }

        #region 数据初始化
        /// <summary>
        /// 数据库初始化
        /// </summary>
        /// <returns></returns>
        public IActionResult Update()
        {
            return View();
        }

        /// <summary>
        /// 系统管理登录
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult LoginUpdate(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return Json(new VmReturn() { Suc = false, Msg = "请输入口令！" });
            }
            if (key != DefaultConstant.Yz + DateTime.Now.ToString(DateFormat.yMd2))
            {
                return Json(new VmReturn() { Suc = false, Msg = "口令无效！" });
            }
            var admin = new VmUserBase()
            {
                Id = 0,
                Name = DefaultConstant.System,
                UserType = UserType.System,
                LoginName = DefaultConstant.System
            };
            var roleList = new List<string>() { UserRoleName.System };
            string token = JwtManager.GenerateToken(admin, roleList, _jwtConfig);
            Response.Cookies.Append("access_token", token);
            return Json(new VmReturn() { Suc = true, Msg = "认证成功！" });
        }
        #endregion


    }
}
